package com.zcxk.web.handler;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.zcxk.common.MultiResponse;
import com.zcxk.constant.Constants;
import com.zcxk.dto.TimeValueDTO;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangping
 * @date 2023-07-28 21:56
 */
public class HistoryTempHandler implements Handler<RoutingContext> {

  private static final Logger logger = LoggerFactory.getLogger(HistoryTempHandler.class);

  private WebClient client;

  public HistoryTempHandler(WebClient client) {
    this.client = client;
  }

  @Override
  public void handle(RoutingContext ctx) {
    String interval = ctx.request().getParam("interval");
    String deviceId = ctx.request().getParam("deviceId");
    HttpRequest<Buffer> request = client.get(Constants.DCP_INTERFACE_HISTORY_TEMP);
    if (Objects.nonNull(interval)) {
      request.addQueryParam("interval", interval);
    }
    if (Objects.nonNull(deviceId)) {
      request.addQueryParam("deviceId", deviceId);
    }
    request.send()
      .onSuccess(response -> {
        if (response.statusCode() != HttpResponseStatus.OK.code()) {
          logger.error("request to dcp server failed, interface: history/temp");
        } else {
          String result = response.bodyAsString();
          List<TimeValueDTO> dtos = JSON.parseArray(result, TimeValueDTO.class);
          ctx.json(MultiResponse.of(dtos));
        }
      }).onFailure(t -> {
        logger.error("request dcp server failure, interface: {}", Constants.DCP_INTERFACE_HISTORY_TEMP, t);
      });
  }
}
